using System.IO;

namespace BLGenerator.BusinessLogic.FileGenerators
{
    public sealed class DBConnectionFileGenerator
    {
        public static void Generate(string filename, Project project)
        {
            StreamWriter stream = new FileInfo(filename).CreateText();
            CompositeFileBlock fileBlock = new CompositeFileBlock();
            fileBlock.Add("using System.Data.SqlClient;");
            fileBlock.Add();
            fileBlock.Add("namespace " + project.Namespace);
            fileBlock.Add("{");
            fileBlock.Add(FileBlock_Class(project));
            fileBlock.Add("}");
            fileBlock.WriteToStream(stream);
            stream.Close();
        }

        private static CompositeFileBlock FileBlock_Class(Project project)
        {
            CompositeFileBlock fileBlock = new CompositeFileBlock();
            fileBlock.Add("public partial class DBConnection");
            fileBlock.Add("{");
            fileBlock.Add(FileBlock_Fields(project));
            fileBlock.Add();
            fileBlock.Add(FileBlock_Properties());
            fileBlock.Add("}");
            return fileBlock;
        }

        private static CompositeFileBlock FileBlock_Fields(Project project)
        {
            CompositeFileBlock fileBlock = new CompositeFileBlock();
            fileBlock.Add(string.Format("private const string _connectionString = @\"{0}\";", project.ResultConnectionString));
            return fileBlock;
        }

        private static CompositeFileBlock FileBlock_Properties()
        {
            CompositeFileBlock fileBlock = new CompositeFileBlock();
            fileBlock.Add("public static SqlConnection Connection");
            fileBlock.Add("{");
            fileBlock.Add(1, "get");
            fileBlock.Add(1, "{");
            fileBlock.Add(2, "SqlConnection connection = new SqlConnection(_connectionString);");
            fileBlock.Add(2, "connection.Open();");
            fileBlock.Add(2, "return connection;");
            fileBlock.Add(1, "}");
            fileBlock.Add("}");
            return fileBlock;
        }
    }
}